package com.zs.grain.ui

import CommonDialog
import android.app.Dialog
import android.app.ProgressDialog
import android.content.DialogInterface
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.text.InputType
import android.text.TextUtils
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.jeremyliao.liveeventbus.LiveEventBus
import com.xnkj1688.semplibrary.dialog.DialogResult
import com.xnkj1688.semplibrary.dialog.InputNumberDialog
import com.xnkj1688.semplibrary.mvvm.BaseMvvmFragment
import com.xnkj1688.semplibrary.recyclerview.ClickHandler
import com.xnkj1688.semplibrary.recyclerview.ItemView
import com.zs.grain.ARouterPath
import com.zs.grain.BR
import com.zs.grain.R
import com.zs.grain.databinding.FragmentTestBinding
import com.zslibrary.BusMaster.BusMaster
import io.reactivex.Single


//import org.jetbrains.anko.*
@Route(path = ARouterPath.TestFragment)
class
TestFragment : BaseMvvmFragment<FragmentTestBinding, TestViewModel>() {

    override val layoutId = R.layout.fragment_test
    //var dlgInput = XDialog(this.activity, R.style.Dialog)
    //var cDialog:CommonDialog.Builder = CommonDialog.Builder(this.context!!)
    override fun initViewModel(binding: FragmentTestBinding) {
        binding.vm = this.mViewModel
        binding.view = this

        LiveEventBus.get("KeyEvent", Boolean::class.java).observe(this, Observer {
            dialog?.dismiss()
            if (wtComponent != -1 && wtId != -1) {
                mViewModel.startTest(wtComponent, wtId)
                wtComponent = -1
                wtId = -1
                showProgressDialog("部件测试", "测试中......",false)
            }
        })
    }

    val selectedBackgroundColor = Color.parseColor("#E0E0E0")//#7FFFD4  #3A9495  #567845
    val selectedBackgroundColor2 = Color.parseColor("#FFFFFF")
    val componentItemView = ItemView<TestItemViewModel>(BR.vm, R.layout.item_list)
    val componentClickHandler = ClickHandler { vm: TestItemViewModel ->
        mViewModel.onClickComponent(vm)
    }
    val testInfoItemView = ItemView<TestItemViewModel>(BR.vm, R.layout.item_list)
    val testInfoItemView2 = ItemView<TestItemViewModel>(BR.vm, R.layout.item_list2)
    val testInfoItemView3 = ItemView<TestItemViewModel>(BR.vm, R.layout.item_list3)
    val testInfoClickHandler = ClickHandler { vm: TestItemViewModel ->

        mViewModel.onClickTestInfo(vm)
    }

    val adjustmentItemView = ItemView<TestItemViewModel>(BR.vm, R.layout.item_list)
    val adjustmentItemView3 = ItemView<TestItemViewModel>(BR.vm, R.layout.item_list3)
    val adjustmentClickHandler = ClickHandler { vm: TestItemViewModel ->
        mViewModel.onClickAdjustment(vm)
    }
    //private val mAlertDialog: AlertDialog? = null
    var testResult = "测试中"
    var dialog: Dialog? = null;
    var resultDialog:Dialog? = null
    var wtComponent: Int = -1
    var wtId: Int = -1
    var wtTimes = -1
    override fun onUiNotify(name: String, bundle: Bundle) {
        super.onUiNotify(name, bundle)
        when (name) {
            "Adjustment" -> {
                val componentId = bundle.getInt("ComponentId")
                val adjustmentId = bundle.getInt("AdjustmentId")
                val componentName = bundle.getString("Name")
                var adjust = mViewModel.getAdjustBean(adjustmentId)
                if (adjust == null) return
                var b = adjust.value / (Math.pow(10.0,adjust.decPoint.toDouble()))
                val dlg = AdjustDialog.newInstance(adjust.title, adjust.min / (Math.pow(10.0,adjust.decPoint.toDouble())), adjust.max / (Math.pow(10.0,adjust.decPoint.toDouble())), adjust.value / (Math.pow(10.0,adjust.decPoint.toDouble())), adjust.unitType)
                val value = dlg.showDialog(this.activity!!.supportFragmentManager, "Adjustment")
                if (value != null && value.toDouble() != (adjust.value*1.0)) {
                    var a = value*Math.pow(10.0,adjust.decPoint.toDouble())
                    mViewModel.saveAdjustment(componentId, adjustmentId,(value*Math.pow(10.0,adjust.decPoint.toDouble())).toInt())//(adjust.value*Math.pow(10.0,adjust.decPoint.toDouble())).toInt()
                }
            }
            "DurationTest"->{
                val componentId = bundle.getInt("ComponentId")
                val Id = bundle.getInt("Id")
                val componentName = bundle.getString("Name")
                val dlg =
                    DurationDialog.newInstance("循环测试", 1, 5, 3)
                val value = dlg.showDialog(this.activity!!.supportFragmentManager, "DurationDialog")
                if(value==null) return
                this.mViewModel.mDataService.insertLog("Operation:component "+componentName)
                mViewModel.startTest(componentId, Id)
            }
            "Calibration" -> {
                val componentId = bundle.getInt("ComponentId")
                val function = bundle.getInt("FunctionIndex")
                val componentName = bundle.getString("Name")
                //wtComponent = bundle.getInt("ComponentId")
                //wtId = bundle.getInt("FunctionIndex")
                val dlg = AdjustDialog.newInstance("校正次数", 1.0, 5.0, 3.0,"")
                val value = dlg.showDialog(this.activity!!.supportFragmentManager, "Adjustment")
                if (value == null) return

                var times = value!!
                wtTimes = value!!.toInt()
                mViewModel.calibrate(componentId, function, times.toInt())

                var dlgInput = InputNumberDialog(this.activity, R.style.Dialog)
                dlgInput.text = ""
                dlgInput.mInputType = InputType.TYPE_CLASS_NUMBER
                if (dlgInput.showDialog() !== DialogResult.OK) return
                this.mViewModel.mDataService.insertLog("Operation:component "+componentName)
                mViewModel.saveCalibration(componentId, times.toInt(), (dlgInput.double * 10).toInt())
                wtComponent = -1
                wtId = -1
                wtTimes = -1
            }
            "ShowProgress" -> {
                //else startTest = true
                showProgressDialog("部件测试", "测试中......",false)
            }
            "ShowProgress2" -> {
                var testResultArray:Array<String> = BusMaster.getInstance(this.context).testString//testString.toString()
                if(testResultArray.size!=0){
                    showProgressDialog("测试结果", testResultArray[0],false)
                }else{
                    showProgressDialog("部件测试", "测试中......",false)
                }
            }
            "HideProgress" -> {
                hideProgressDialog()
            }
            "testResult"->{
                val tResult = bundle.getString("tResult")
                resultDialog = CommonDialog.Builder(this.context!!)
                    .setTitle(tResult)
                    .setOtherButton("下一步2",DialogInterface.OnClickListener{p0,p1->
                        p0?.dismiss()

                    })
                    .setPositiveButton("确定2", DialogInterface.OnClickListener { p0, p1 ->
                        p0?.dismiss()
                    })
                    .setNegativeButton("取消2", DialogInterface.OnClickListener { p0, p1 ->
                        p0?.dismiss()
                    })
                    .setWith(1.0f)
                    .create(
                        false,
                        R.layout.dialog_toast,
                        R.id.yesButton,
                        R.id.noButton
                    );
                dialog?.show()
            }
            "Duration"->{
                val componentId = bundle.getInt("ComponentId")
                val Id = bundle.getInt("Id")
                val componentName = bundle.getString("Name")
                dialog = CommonDialog.Builder(this.context!!)
                    //.setTitle("循环测试")
                    //.setTitle2("点击确定开始测试,\n测试中点击取消中止")
                    .setPositiveButton("确定", DialogInterface.OnClickListener { p0, p1 ->
                        dialog = CommonDialog.Builder(this.context!!)
                            .setTitle("测试中...")
                            .setPositiveButton("取消", DialogInterface.OnClickListener { p0, p1 ->
                                p0?.dismiss()
                                BusMaster.getInstance(context).cancelDurationTest(componentId.toShort(), Id.toShort())
                            })
                            .setWith(1.0f)
                            .create(
                                false,
                                R.layout.dialog_toast2,
                                R.id.yesButton
                            );
                        dialog?.show()
                        this.mViewModel.mDataService.insertLog("Operation:component "+componentName)
                        mViewModel.startTest(componentId, Id)
                    })
                    .setNegativeButton("取消", DialogInterface.OnClickListener { p0, p1 ->
                        p0?.dismiss()

                    })
                    .setWith(1.0f)
                    .create(
                        false,
                        R.layout.dialog_toast,
                        R.id.yesButton,
                        R.id.noButton
                    );
                dialog?.show()
            }
            "SelectDialog" -> {
                val componentId = bundle.getInt("ComponentId")
                wtComponent = bundle.getInt("ComponentId")
                val Id = bundle.getInt("Id")
                wtId = bundle.getInt("Id")
                val componentName = bundle.getString("Name")
                dialog = CommonDialog.Builder(this.context!!)
                    .setPositiveButton("确定", DialogInterface.OnClickListener { p0, p1 ->
                        p0?.dismiss()
                        this.mViewModel.mDataService.insertLog("Operation:component "+componentName)
                        this.onUiNotify("ShowProgress", Bundle())
                        mViewModel.startTest(componentId, Id)
                        wtComponent = -1
                        wtId = -1
                    })
                    .setNegativeButton("取消", DialogInterface.OnClickListener { p0, p1 ->
                        p0?.dismiss()
                        wtComponent = -1
                        wtId = -1
                    })
		            .setOtherButton("使用功能按键 >", DialogInterface.OnClickListener { p0, p1 ->p0?.dismiss()})
                    .setWith(1.0f)
                    .create(
                        false,
                        R.layout.dialog_toast,
                        R.id.yesButton,
                        R.id.noButton,
                        R.id.otherButton
                    )
                dialog?.show()
            }
        }
    }

    internal var progressingView: ProgressDialog? = null
    // 显示进度
    fun showProgressDialog(title: String, msg: String,canCancel:Boolean) {
        if (TextUtils.isEmpty(msg) || TextUtils.isEmpty(title)) {
            return
        }
        if (progressingView == null) {
            progressingView = ProgressDialog(this.activity)//1.创建一个ProgressDialog的实例
        }
        progressingView!!.setTitle(title)//2.设置标题
        progressingView!!.setMessage(msg)
        //progressingView!!.setCancelable(false)//4.设置可否用back键关闭对话框
        progressingView!!.setCanceledOnTouchOutside(canCancel)//点击其它地方不能隐藏
        progressingView!!.show()
    }

    fun hideProgressDialog() {
        if (progressingView == null) {
            return
        }
        progressingView!!.hide()
    }
}
